<?php

/*
  Aurus CMS - free OOP CMS
  Copyright (C) 2010  Nestor Yanchuk

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class Module_forum implements Module {

    public function run() {
	Aurus::getInstance()->addContent($this->render());
    }

    public function onActivate() {

    }

    public function onDeactivate() {

    }

    public function initAdminArea() {

    }

    public function runAjax() {
	
    }

    private $sql = array();
    /**
     * @var Template
     */
    private $tpl = null;

    public function __construct() {
	$this->tpl = Template::getInstance();
    }

    public function showMain() {
	$this->tpl->load('forum/main');
	//	$this->tpl->set('{BOARD}', );
	$this->tpl->set('{now_time}', au_date(Config::get('timeFormat')));

	if (Users::getInstance()->is_logged()) {
	    $this->tpl->set('[useronly]');
	    $this->tpl->set('[/useronly]');
	    $this->tpl->set('{user}', Users::getInstance()->getLoggedUsersData('login'));
	    $this->tpl->set('{user_lastvisit}', au_date('d/m/Y H:i', Users::getInstance()->getLoggedUsersData('last_visit'))); //TODO: time format from config
	} else {
	    $this->tpl->deleteBlock('useronly');
	}

	return $this->tpl->out();
    }

    public function showCategory($cat = 0) {
	if ($cat) {
	    $query = "(type IN('cat','forum')) AND (fid=" . $cat . ' OR parent=' . $cat . ' )';
	} else {
	    $query = "type IN('cat','forum')";
	}

	$f_cat = Mysql::getInstance()->select('forum_data', '*', $query);
	$tpl = Template::getInstance();
	$CAT = array();

	for ($i = 0, $n = count($f_cat); $i < $n; $i++) {
	    $finfo = $f_cat[$i];
	    if ($finfo['type'] == 'forum') {
		$tpl->load('forum/forums');
		$tpl->set('{name}', '<a href="' . Url::formatUrl('forum', array('viewforum' => $finfo['fid']), 1) . '">' . $finfo['name'] . '</a>');
		$tpl->set('{description}', $finfo['desc']);
		$tpl->set('{topics}', $finfo['topics_c']);
		$tpl->set('{post}', $finfo['posts_c']);
		$tpl->set('{last}', 'last');
		$tpl->set('{status}', $this->getForumStatus($finfo['updated_time']));

		if (!isset($CAT[$finfo['parent']])) {
		    $CAT[$finfo['parent']] = '';
		}

		$CAT[$finfo['parent']] .= $tpl->out();
	    }
	}

	for ($i = 0, $n = count($f_cat); $i < $n; $i++) {
	    $finfo = $f_cat[$i];
	    if ($finfo['type'] == 'cat') {
		$tpl->load('forum/category');
		$tpl->set('{category}', '<a href="' . Url::formatUrl('forum', array('viewcategory' => $finfo['fid']), 1) . '">' . $finfo['name'] . '</a>');
		$tpl->set('{forums}', isset($CAT[$finfo['fid']]) ? $CAT[$finfo['fid']] : '');
		Aurus::getInstance()->addContent($tpl->out());
	    }
	}

	return $this->showMain();
    }

    public function render() {
	switch ($this->getPageToShow()) {
	    case 'category':
		return $this->showCategory((int) $_GET['viewcategory']);
		break;
	    case 'forum':
		return $this->showForum((int) $_GET['viewforum']);
		break;
	    case 'topic':
		return $this->showTopic((int) $_GET['viewtopic']);
		break;
	    case 'main':
		return $this->showCategory();
		break;
	    case 'post':
		return;
		break;
	    case 'servise':

		break;
	}
    }

    private function getPageToShow() {
	if (isset($_GET['viewcategory']))
	    return 'category';
	if (isset($_GET['viewforum']))
	    return 'forum';
	if (isset($_GET['viewtopic']))
	    return 'topic';
	if (isset($_GET['viewpost']))
	    return 'post';
	if (isset($_GET['servise']))
	    return 'servise';
	return 'main';
    }

    private function getForumStatus($updateTime) {
	$lastLogin = Users::getInstance()->getLoggedUsersData('last_login');
	if ($lastLogin > $updateTime) {
	    return '<img src="{THEME}/forum/images/forum_old.gif" alt="' . __('Немає нових повідомленнь') . '"/>';
	} else {
	    return '<img src="{THEME}/forum/images/forum_new.gif" alt="' . __('Є нові повідомлення') . '"/>';
	}
    }

    private function showForum($id) {
	$fdata = Mysql::getInstance()->select('forum_data', '*', 'fid=' . $id);
	$tpl = Template::getInstance();
	$fdata = $fdata[0];
	//debug($fdata);

	$gp = $this->getTopics((int) $_GET['viewforum']);

	$tpl->load('forum/forum');

	if ($fdata['rules']) {
	    $tpl->set('{rules-text}', $fdata['rules']);
	    $tpl->set('[rules]');
	    $tpl->set('[/rules]');
	} else {
	    $tpl->deleteBlock('rules');
	}

	if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('uid'), 'addForumThreads')) {
	    $tpl->set('[/new_topic]');
	    $tpl->set('[new_topic]');
	} else {
	    $tpl->deleteBlock('[/new_topic]');
	}

	$tpl->set('{forum}', $fdata['name']);
	$tpl->set('{topics}', $gp);

	return $tpl->out();
    }

    private function getTopics($forumId) {
	$posts = ORM::connect('forum_data')->join('users', 'updated_user', 'uid')->parent($forumId)->type('topic')->get()->toArray();
	//debug($posts);
	$ret = '';
	$tpl = Template::getInstance();

	foreach ($posts as $key => $value) {
	    $tpl->load('forum/topics');
	    $tpl->set('{title}', $value['name']);
	    $tpl->set('{description}', $value['desc']);
	    $tpl->set('{post}', $value['posts_c']);
	    $tpl->set('{status}', $this->getTopicStatus($value['updated_time']));
	    $tpl->set('{author}', $value['login']);
	    $tpl->set('{views}', $value['views']);
	    $tpl->set('{last}', $value['login']);

	    $tpl->set('[topic]', '<a href="' . Url::formatUrl('forum', array('viewtopic' => $value['fid'])) . '">');
	    $tpl->set('[/topic]', '</a>');

	    $tpl->setArrayTag('data', $value);
	    $ret .= $tpl->out();
	}

	return $ret;
    }

    private static function getTopicStatus($updateTime) {
	$new = '<img src="{THEME}/forum/images/topic_old.gif" alt="' . __('Оновлена тема') . '" />';
	$old = '<img src="{THEME}/forum/images/topic_old.gif" alt="' . __('Стара тема') . '" />';

	if (Users::getInstance()->getLoggedUsersData('last_visit') - $updateTime < 0) {
	    return $new;
	} else {
	    return $old;
	}
    }

    private function showTopic($id) {
	$posts = ORM::connect('forum_posts')->join('users', 'author', 'uid')->parent_topic($id)->get()->toArray();
	$tpl = Template::getInstance();
	$allPosts = '';
	//debug($posts);
	foreach ($posts as $post) {
	    $tpl->load('forum/post');
	    $tpl->set('{post-id}', $post['p_id']);
	    $tpl->set('{author}', $post['login']);
	    $tpl->set('{date}', au_date('d/m/Y H:I', $post['time'])); //TODO: time format from config
	    $tpl->set('{avatar}', $post['avatar']);
	    $tpl->set('{text}', $post['message']);

	    $tpl->set('{post-id}', $post['p_id']);
	    $tpl->set('{post-id}', $post['p_id']);

	    if ($post['signature']) {
		$tpl->set('{signature}', $post['signature']);
		$tpl->set('[signature]');
		$tpl->set('[/signature]');
	    } else {
		$tpl->deleteBlock('signature');
	    }

	    $allPosts .= $tpl->out();
	}

	$tpl = Template::getInstance();
	$tpl->load('forum/topic');
	$tpl->set('{posts}', $allPosts);

	Aurus::getInstance()->addContent($tpl->out());
    }

}